import React, {FC, Key, useEffect, useMemo, useRef, useState} from 'react';
import "./index.less";
import * as API from "@/services";
import {useRequest} from "ahooks";
import HxLineCollapse from "@/components/HxLineCollapse";
import classNames from "classnames";
import {FormattedMessage} from "@@/exports";


interface MallJournalPeriodItemProps {
  item: API.FrontJournalPeriod;
  checked?: boolean;
  onChange?: (checked: boolean) => void;
}

const MallJournalPeriodPickerItem: FC<MallJournalPeriodItemProps> = (props) => {
  const {item, checked, onChange} = props;
  return (
    <a className={classNames("mall-journal-period-item", {"active": checked})} onClick={(e) => {
      e.preventDefault();
      onChange?.(!checked);
    }}>
      <FormattedMessage id="journal.period-info.period-desc" values={{year: item.year, volume: item.volume, period: item.period}}/>
    </a>
  );
};

export interface MallJournalPeriodPickerValueType {
  value: API.EntityId,
  label: string;
}

interface HxJournalPeriodPickerProps {
  journalId: API.EntityId;
  value?: MallJournalPeriodPickerValueType[],
  onChange?: (value: MallJournalPeriodPickerValueType[]) => void,
}

/**
 * 期刊往期选取器 页面
 */
const HxJournalPeriodPicker: FC<HxJournalPeriodPickerProps> = (props) => {
  const {journalId, value, onChange} = props;

  const activeKeyInitialized = useRef(false);
  const [activeKey, setActiveKey] = useState<Key[]>([])
  const [itemsMap, setItemsMap] = useState<Record<string, API.FrontJournalPeriod[]>>({})

  const [pastYears, setPastYears] = useState(5);
  const [displayedAllYear, setDisplayedAllYear] = useState(false);

  const statsReq = useRequest(() => API.queryFrontJournalPeriodYearStat(journalId!), {
    refreshDeps: [journalId]
  });
  const stats = statsReq.data?.data || [];

  useEffect(() => {
    if (!activeKeyInitialized.current && activeKey.length === 0 && stats.length > 0) {
      setActiveKey([`${stats[0].year}`])
      activeKeyInitialized.current = true;
    }
  }, [stats]);

  useEffect(() => {
    const process = async () => {
      if (activeKey.length > 0) {
        for (const k of activeKey) {
          const items = itemsMap[`${k}`];
          if (!items) {
            const resp = await API.queryFrontJournalPeriods({journalId, year: Number(k), pageSize: 1000});
            itemsMap[`${k}`] = resp.data || [];
          }
          setItemsMap({...itemsMap})
        }
      }
    };
    process();
  }, [activeKey]);

  const collapseItems = useMemo(() => {
    return stats
      .filter((item, itemIndex) => {
        if (displayedAllYear) {
          return true;
        }
        return itemIndex < pastYears;
      }).map(stat => {
        const key = `${stat.year}`;
        const items = itemsMap[key]
        return {
          key: key,
          label: (
            <div className={"mall-jp-collapse-year-item-header"}>
              <div className={"mall-jp-collapse-year-item-title"}>
                <FormattedMessage id="journal.period-info.aggregate-by-year-desc" values={{year: stat.year}}/>
              </div>
              <div className={"mall-jp-collapse-year-item-tj"}>
                （ <FormattedMessage id="journal.period-info.aggregate-by-issue-desc" values={{total: stat.periodNum}}/>）

              </div>
            </div>
          ),
          children: <div className={"mall-jp-collapse-items"}>
            {
              items?.map((item, itemIndex) => {
                const checked = (value || []).findIndex(v => v.value === item.id) !== -1;
                return (
                  <MallJournalPeriodPickerItem key={item.id} item={item} checked={checked} onChange={(c) => {
                    if (c) {
                      onChange?.([...(value || []), {value: item.id, label: item.periodName}]);
                    } else {
                      onChange?.((value || []).filter(v => v.value !== item.id));
                    }
                  }}/>
                )
              })
            }
          </div>
        }
      })
  }, [stats, itemsMap, value, pastYears, displayedAllYear])

  return (
    <div className={"hx-journal-period-picker-container"}>
      {
        collapseItems.length > 0 ? (
            <>
              <HxLineCollapse
                className={"mall-jp-collapse"}
                activeKey={activeKey as string[]}
                onChange={setActiveKey}
                ghost
                items={collapseItems}
              />
              {
                (!displayedAllYear && stats.length > pastYears) && (
                  <a className={"show-more-years-btn"} onClick={(e) => {
                    e.preventDefault();
                    setDisplayedAllYear(true)
                  }}><FormattedMessage id="journal.period-info.more"/></a>
                )
              }
            </>
          ) :
          (
            <div className={"hx-journal-period-picker-empty"}>当前期刊没有往期数据</div>
          )
      }

    </div>
  );
};

export default HxJournalPeriodPicker;
